const tb = document.querySelector('.list')
// 模态框下拉列表
const province = document.querySelector('[name="province"')
const city = document.querySelector('[name="city"')
const area = document.querySelector('[name="area"')
const submit = document.querySelector('#submit')
// 获取学生总数标签
const total = document.querySelector('.total')
// 获取数据和渲染数据
async function getList () {
  const result = await axios({
    url: '/students',
  })
  // console.log(result.data.data)
  const arr = result.data.data
  let randerHTML = ''
  for (const key in arr) {
    const { id, name, age, gender, group, hope_salary, salary, province, city, area } = arr[key]
    const Gender = gender === 1 ? '女' : '男'

    randerHTML += `
                    <tr>
                      <td>${name}</td>
                      <td>${age}</td>
                      <td>${Gender}</td>
                      <td>${group}</td>
                      <td>${hope_salary}</td>
                      <td>${salary}</td>
                      <td>${province}${city}${area}</td>
                      <td>
                        <a href="javascript:;" class="text-success mr-3"><i data-id="${id}" class="bi bi-pen"></i></a>
                        <a  href="javascript:;" class="text-danger"><i data-id="${id}" class="bi bi-trash"></i></a>
                      </td>
                    </tr>`
  }
  tb.innerHTML = randerHTML
  total.innerHTML = arr.length
}
getList()

// 打开模态框
const openModal = document.querySelector('#openModal')
// 模态框form 表单
const form = document.querySelector('#form')
// 实例化模态框
const modal = new bootstrap.Modal(document.querySelector('#modal'))
openModal.addEventListener('click', async function () {
  // 把模态框切换回添加学员
  document.querySelector('.modal-title').innerHTML = '添加学员'
  // 重置表单
  form.reset()
  // 重新渲染市和区列表
  await getCity()
  await getArea()
  // 展示模态框
  modal.show()
})
// 封装省市县下拉框函数
async function getSelect (url, params, text, target) {
  const result = await axios({
    url,
    params
  })
  // console.log(result.data.data)
  const arr = result.data.data
  target.innerHTML = arr.reduce((getSum, value) => {
    return getSum + `
    <option value="${value}">--${value}--</option>`
  }, `<option value="">--${text}--</option>`)
}

// 获取省份数据
async function getProvince () {

  getSelect('/api/province', {}, '省', province)
}
getProvince()
// 获取城市数据
async function getCity (pname) {
  // 相当于调用getCity() 函数时，直接调用getSelect() 函数
  return getSelect('/api/city', { pname }, '市', city)
}
getCity()
// 获取地区数据
async function getArea (pname, cname) {
  // 相当于调用getArea() 函数时，直接调用getSelect() 函数
  return getSelect('/api/area', { pname, cname }, '县', area)
}
getArea()
// 当下拉框发生改变时
province.addEventListener('change', async function () {
  await getCity(province.value)
  const city = document.querySelector('[name="city"]')
  await getArea(province.value, city.value)
})
city.addEventListener('change', function () {
  const city = document.querySelector('[name="city"]')
  getArea(province.value, city.value)
})

// 删除数据按钮和修改数据按钮
let uesrId = 0
tb.addEventListener('click', async function (e) {
  if (e.target.classList.contains('bi-trash')) {
    uesrId = e.target.dataset.id
    const result = await axios({
      url: `/students/${uesrId}`,
      method: 'delete'
    })

    getList()
  } else if (e.target.classList.contains('bi-pen')) {
    document.querySelector('.modal-title').innerHTML = '修改学生'
    uesrId = e.target.dataset.id
    const result = await axios({
      url: `/students/${uesrId}`,
      params: {
        id: uesrId
      }
    })

    const obj = result.data.data
    await getCity(obj.province)
    await getArea(obj.province, obj.city)

    for (const key in obj) {
      const getEle = document.querySelector(`[name="${key}"]`)

      if (getEle && key !== 'gender') {
        // 这里有些渲染不上去
        getEle.value = obj[key]
      } else if (key === 'gender') {
        document.querySelector(`[name='${key}'][value='${obj[key]}']`).checked = true
      }
    }
    // 展示模态框
    modal.show()
  }
})

// 点击模拟框确认按钮收集表单数据或更改数据
submit.addEventListener('click', async function () {
  const title = document.querySelector('.modal-title').innerHTML
  const formList = new FormData(form)
  let obj = {}
  formList.forEach((value, index) => {
    // arr.push(`${index}=${value}`)
    obj[index] = value
  })

  const { name, gender, age, group, hope_salary, salary, province, city, area } = obj
  let result
  // 通过h5标题内容判断进行：添加学员还是修改学员操作
  if (title === '添加学员') {
    const id = parseInt(Date.now() % 1677700000000 / 1000)
    // 上传数据
    result = await axios({
      url: '/students',
      method: 'post',
      data: {
        id,
        name,
        age: +age,
        gender: +gender,
        province,
        city,
        area,
        hope_salary: +hope_salary,
        salary: +salary,
        group: +group
      }
    })
  } else if (title === '修改学生') {
    // 上传数据
    result = await axios({
      url: `/students/${uesrId}`,
      method: 'put',
      data: {
        name,
        age: +age,
        gender: +gender,
        province,
        city,
        area,
        hope_salary: +hope_salary,
        salary: +salary,
        group: +group
      }
    })
  }
  // console.log(result)
  if (result.status === 201 || result.status === 200) {
    document.querySelector('#myToast .toast-body').innerHTML = result.data.message
    myToast.show()
  }
  getList()
  // 关闭模态框
  modal.hide()
  // 重置表单
  form.reset()

})